const app = getApp();
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

function getCurrentPageOptions() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var options = currentPage.options
    return options
}

function getCurrentPageUrl() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    return url
}

function getCurrentPageUrlWithArgs() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options //如果要获取url中所带的参数可以查看options

    //拼接url的参数
    var urlWithArgs = url + '?'
    for (var key in options) {
        var value = options[key]
        urlWithArgs += key + '=' + value + '&'
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

    return urlWithArgs
}

function share() {
    var params = getCurrentPageOptions();
    if (params.share_key) {
        wx.setStorage({
            key: 'share_key',
            data: params.share_key
        })
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=wx_share&op=click_reward',
            data: {
                share: 1,
                key: params.share_key,
                type: 'wechat',
                link: getCurrentPageUrlWithArgs()
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            success: (res) => {

            }
        });
    }
}
const timestampToTime = (timestamp) => {
    var date = new Date(timestamp * 1000); //时间戳位数为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
}

function clock(endTime) {
    //现在时间;
    var now = new Date();
    //时间差:总的秒数(1000毫秒等于1秒);
    var lastTime = parseInt((endTime - now) / 1000);
    if (lastTime != 0) {
        //时间转换;
        var day = parseInt((lastTime / 60 / 60 / 24 % 24));
        var hour = parseInt((lastTime / 60 / 60 % 24));
        var min = parseInt((lastTime / 60 % 60));
        var sec = parseInt((lastTime % 60));
    }
    return {
        'day': addZero(day),
        'hour': addZero(hour),
        'min': addZero(min),
        'sec': addZero(sec)
    }
}

function addZero(num) {
    if (num < 10) {
        num = '0' + num;
    }
    return num;
}

function tabCalCartNum() {
    wx.getStorage({
        key: 'cart_count',
        success: (res) => {
            if (res.data > 0) {
                wx.setTabBarBadge({
                    index: 3,
                    text: String(res.data)
                })
            } else {
                wx.removeTabBarBadge({
                    index: 3,
                })
            }

        },
    })
}


function buildUrl(type, data) {
    switch (type) {
        case 'keyword':
            return '/pages/search/search?keyword=' + encodeURIComponent(data);
        case 'special':
            return '/pages/special/special?special_id=' + data;
        case 'goods':
            return '/pages/goods_detail/goods_detail?goods_id=' + data;
        case 'goods_class':
            return '/pages/search/search?cate_id=' + data;
        case 'brand':
            return '/pages/search/search?b_id=' + data;
        case 'store':
            return '/pages/store/store?store_id=' + data;
        case 'url':
            return data;
    }
    return '/pages/index/index';
}

function parseURL(url) {
    if (url.indexOf('?') != -1) {
        var str = url.split('?')[1],
            items = str.split('&'),
            result = {},
            res = {};
        for (var i = 0, len = items.length; i < len; ++i) {
            res = items[i].split("=");
            result[res[0]] = res[1];
        }
        return result;
    }
}

function wx_scan() {
    wx.scanCode({
        success(res) {
            var params = parseURL(res.result);
            let redirectUrl = '';
            if (res.result.indexOf("https://i.bdyoo.com") != -1) {
                if (params.goods_id && res.result.indexOf("product_detail.html") != -1) {
                    redirectUrl = "/pages/goods_detail/goods_detail?goods_id=" + params.goods_id
                } else if (params.store_id && res.result.indexOf("store.html") != -1) {
                    redirectUrl = "/pages/store/store?store_id=" + params.store_id
                } else if (params.special_id && res.result.indexOf("special.html") != -1) {
                    redirectUrl = "/pages/special/special?special_id=" + params.special_id
                } else if (params.rpacket_id && res.result.indexOf("redpacket_qrcode.html") != -1) {
                    redirectUrl = "/pages/rpacket/rpacket?rpacket_id=" + params.rpacket_id
                } else if (params.id && res.result.indexOf("rechargecard_qrcode.html") != -1) {
                    redirectUrl = "/pages/rechargecard/rechargecard?rechargecard_id=" + params.id
                } else {
                    redirectUrl = "/pages/index/index"
                }

            }

            wx.navigateTo({
                url: redirectUrl
            })
        }
    })
}
module.exports = {
    timestampToTime: timestampToTime,
    formatTime: formatTime,
    getCurrentPageUrlWithArgs: getCurrentPageUrlWithArgs,
    getCurrentPageOptions: getCurrentPageOptions,
    share: share,
    clock: clock,
    tabCalCartNum: tabCalCartNum,
    buildUrl: buildUrl,
    wx_scan: wx_scan,
}